package com.hup.utils.swing.customView.colorChooser;

import com.hup.utils.commons.start.LookThemeUtil;
import lombok.extern.log4j.Log4j2;

import java.awt.*;
import java.awt.image.MemoryImageSource;

/**
 * [邻近色]色板
 * @author hugan
 * @date 2020/4/10
 */
@Log4j2
public class NearColorLabel extends AbsColorLabel {

    public NearColorLabel() {
        Dimension dimension = new Dimension(-1, (int) (25 * LookThemeUtil.getScreenScale()));
        setPreferredSize(dimension);
        setMinimumSize(dimension);
    }

    @Override
    protected int[] initPix() {
        return new int[9];
    }

    @Override
    protected Image updateImageByColor() {
        log.debug("");
        int a = color.getAlpha();
        int r = color.getRed();
        int g = color.getGreen();
        int b = color.getBlue();

        int step = (int) (255 / 9.0);
        for (int i = 1; i <= 9; i++) {
            int diff = 0;
            if (i < 5) {
                diff = -(5 - i) * step;
            } else if (i > 5) {
                diff = (i - 5) * step;
            }
            int r2 = fix(r + diff);
            int g2 = fix(g + diff);
            int b2 = fix(b + diff);
            //log.info("diff={}, r2={}, g2={}, b2={}", diff, r2, g2, b2);
            pix[i - 1] = a << 24 | r2 << 16 | g2 << 8 | b2;
        }
        return createImage(new MemoryImageSource(9, 1, pix, 0, 9));
    }

    @Override
    public boolean doPaintGraphics(Graphics g) {
        g.drawImage(image, 0, 0, width, height, null);

        //游标,总是水平居中的
        Polygon p = new Polygon();//倒三角
        g.setColor(CURSOR_COLOR_C1);
        int curX = width / 2;
        int h2 = height / 4;
        p.addPoint(curX - h2, 0);//左
        p.addPoint(curX + h2, 0);//右
        p.addPoint(curX, height / 6 * 2);//底点
        g.fillPolygon(p);

        p.reset();
        g.setColor(CURSOR_COLOR_C2);
        p.addPoint(curX, height / 6 * 4);//左顶点
        p.addPoint(curX - h2, height);//左
        p.addPoint(curX + h2, height);//右
        g.fillPolygon(p);
        return true;
    }

    @Override
    protected Color getMouseColor(boolean isPress, int x, int y) {
        if (!isPress) return null;

        int curI = getMxIndex(x);
        log.debug("x={}, y={}, curI={}", x, y, curI);

        return new Color(pix[curI], true);
    }

    private int fix(int v) {
        if (v < 0) {
            return 0;
        } else if (v > 255) {
            return 255;
        } else {
            return v;
        }
    }

}
